package com.ala4.oxcafe.boot.utils;

import com.ala4.oxcafe.boot.authentication.CustomAuthenticationToken;
import com.ala4.oxcafe.boot.manager.CustomUserDetails;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 根据请求解析出userDetail和clientDetail对象
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/20 16:24
 */
public class DetailsHelper {

    private DetailsHelper() {
    }

    /**
     * {@inheritDoc}
     * 获取访问用户的userDetail对象
     *
     * @return CustomUserDetails
     */
    public static CustomUserDetails getUserDetails() {
        if (SecurityContextHolder.getContext() == null
                || SecurityContextHolder.getContext().getAuthentication() == null) {
            return null;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof CustomUserDetails) {
            return (CustomUserDetails) principal;
        }
        return null;
    }

    /**
     * 设置一个用户信息
     *
     * @param customUserDetails
     */
    public static void setCustomUserDetails(CustomUserDetails customUserDetails) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext == null) {
            return;
        }
        securityContext.setAuthentication(new CustomAuthenticationToken(customUserDetails));
    }

    /**
     * 清理上下文
     */
    public static void clearContext() {
        SecurityContextHolder.clearContext();
    }
}
